import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: sessionStorage.getItem('state') ? JSON.parse(sessionStorage.getItem('state')) : {
    active: "home",
    goods: [],

  },
  mutations: {
    addgoods(state, obj) {
      var i = state.goods.findIndex(x => {
        return x.id == obj.id
      })
      if (i == -1) {
        state.goods.push(obj)
      } else {
        state.goods[i].cou += obj.cou
      }
    },
    changegoods(state, item) {
      var i = state.goods.findIndex(x =>
        x.id == item.id
      )
      if (i != -1) {
        state.goods[i].cou = item.cou
      } else {
        alert("没有找到商品")
      }
    },
    delgoods(state, id) {
      var i = state.goods.findIndex(x =>
        x.id == id)
      state.goods.splice(i, 1)

    }
  },
  actions: {
  },
  getters: {
    ids(state) {
      var goodsids = [];
      state.goods.forEach(x => {
        goodsids.push(x.id);
      });
      return goodsids.join(",");
    },
    mount(state) {
      var ss = 0
      state.goods.forEach(x =>
        ss += x.cou)
      return ss
    }

  },
  modules: {
  }
})
